package org.example.netty.client;


import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.HexUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageCodec;
import org.example.netty.model.JsonRespMsg;
import org.example.netty.model.JsonSendMsg;

import java.nio.charset.StandardCharsets;
import java.util.List;

public class MessageCodec extends ByteToMessageCodec<JsonSendMsg> {
    @Override
    protected void encode(ChannelHandlerContext ctx, JsonSendMsg msg, ByteBuf out) throws Exception {
        // 包头
        out.writeBytes("<?begn?>".getBytes(StandardCharsets.UTF_8));
        // 业务类型
        out.writeBytes(new byte[]{1, 0});
        // 保留两个字节
        out.writeBytes(new byte[]{2, 0});
        // 包长度
        String jsonStr = JSONUtil.toJsonStr(msg);
        byte[] msgByte = jsonStr.getBytes();
        int packetLength = msgByte.length + 64;
        byte[] lengthByte = Convert.hexToBytes(HexUtil.toHex(packetLength));
        out.writeBytes(new byte[]{0, 0});
        if (lengthByte.length == 2) {
            out.writeBytes(lengthByte);
        } else {
            out.writeBytes(new byte[1]);
            out.writeBytes(lengthByte);
        }
        // Json字符串
        out.writeBytes(msgByte);
        // 64位签名
        byte[] signByte = new byte[64];
        out.writeBytes(signByte);
        // 包尾
        out.writeBytes("<?endn?>".getBytes(StandardCharsets.UTF_8));
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List out) throws Exception {
        // 8个字节的包头
        byte[] bhead = new byte[8];
        in.readBytes(bhead, 0, 8);
        String packetHead = new String(bhead, StandardCharsets.UTF_8);
        if (!ObjectUtil.equal("<?begn?>",packetHead)) {
            return;
        }
        // 2个自己的业务类型
        byte[] btype = new byte[2];
        in.readBytes(btype, 0, 2);
        // 2个字节的保留字段
        byte[] bnone = new byte[2];
        in.readBytes(bnone, 0, 2);
        // 四个字节的长度
        int length = in.readInt();
        //实际内容
        length = length - 64;
        byte[] jsonMsg = new byte[length];
        in.readBytes(jsonMsg, 0, length);
        String msgStr = new String(jsonMsg, StandardCharsets.UTF_8);
        JsonRespMsg jsonRespMsg = JSONUtil.toBean(msgStr, JsonRespMsg.class);
        out.add(jsonRespMsg);

    }
}
